package com.ma.handler;

import java.util.concurrent.atomic.AtomicInteger;

import com.ma.entity.ProtostuffUtils;
import com.ma.rpc.RPCCallBack;
import com.ma.rpc.RpcFuture;
import com.ma.rpc.RpcResponse;
import com.ma.rpc.RpcThreadPool;
import com.server.java.entity.MsgEntity;

import io.netty.channel.ChannelHandlerContext;

public class RPCHandlerClient extends MyHandler {

	//public static final AtomicInteger workerIndex = new AtomicInteger(); 
	@Override
	public void doHandler(ChannelHandlerContext arg0, MsgEntity arg1) {
		RpcResponse response = ProtostuffUtils.deserialize(arg1.getData(), RpcResponse.class);
		String idString = response.getKey();
		RPCCallBack back = RpcThreadPool.getRpcThreadPool().getCallBack(idString);
		if (back != null) {

			back.setResult(response);
			RpcThreadPool.getRpcThreadPool().removeCallBack(idString);
		} else {

			RpcFuture f = RpcThreadPool.getRpcThreadPool().getFuture(idString);
			if (f == null) {
				arg0.channel().close();
				System.exit(1);
				return;
			}
			f.start(response, RpcThreadPool.getRpcThreadPool().getWork());
			RpcThreadPool.getRpcThreadPool().removefuture(idString);
		}

	}

}
